package com.java.base.exercise.disruptor;

import com.lmax.disruptor.EventTranslatorOneArg;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.SleepingWaitStrategy;
import com.lmax.disruptor.WaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.Executors;

/**
 * @Author RenPu
 * @Date 2023/10/25 14:49
 * @Version 1.0
 * @Description:Disruptor测试类得编写        disruptor高性能内存框架demo得编写
 **/
public class DisruptorMain {

    public static void main(String[] args) {

        //创建事件工厂给对象
        EventFactory factory = new EventFactory();

        //设置ringBuffer得大小
        int bufferSize=2048;

        //创建Disruptor，设置初始化得参数
        Disruptor<LongEvent> eventDisruptor = new Disruptor<LongEvent>(
                factory,
                bufferSize,
                Executors.defaultThreadFactory(),
                ProducerType.SINGLE,                   //消息生产方的模式类型设置（一般建议设置为单例，
                                                       // 因为消息消息的存储使用了无锁化，使用了CAS如果多个生产者很有可能频繁触发CAS引起CPU的占用偏高）
                new SleepingWaitStrategy()            //当读写指针处于临界值，等待的方式
        );

        //绑定消费者
        eventDisruptor.handleEventsWith(new LongEventHandler());

        //启动eventDisruptor对象
         eventDisruptor.start();

        //获取eventDisruptor的ringBuffer,消息生产者将消息包装为event类型进行存储
        RingBuffer<LongEvent> ringBuffer = eventDisruptor.getRingBuffer();
        LongEventProducterWithTranslator longEventProducterWithTranslator = new LongEventProducterWithTranslator(ringBuffer);


        for (int i = 0; i <100 ; i++) {

            long value = (long)(Math.random() * 10000) + 1;
            longEventProducterWithTranslator.onData(value);

        }

        eventDisruptor.shutdown();


    }
}
